import * as SignalR from '@microsoft/signalr';
import { Local } from './storage';
import { REFRESH_ACCESS_TOKEN_KEY, TOKEN_KEY } from '@/const';

export const getToken = ()=>Local.get(TOKEN_KEY);
export const getRefreshToken = ()=>Local.get(REFRESH_ACCESS_TOKEN_KEY)

const connection = new SignalR.HubConnectionBuilder()
    .configureLogging(SignalR.LogLevel.Information)
    .withUrl(`${import.meta.env.VITE_API_URL}/hubs/onlineUser?token=${getToken()}`, {
        transport: SignalR.HttpTransportType.WebSockets,
        skipNegotiation: true,
    })
    .withAutomaticReconnect({
        nextRetryDelayInMilliseconds: () => {
			return 5000; // 每5秒重连一次
		},
    })
    .build();

connection.keepAliveIntervalInMilliseconds = 15 * 1000; // 每15秒发送一次心跳包
connection.serverTimeoutInMilliseconds = 30 * 60 * 1000; // 服务器超时时间为30分钟

// 启动连接
connection.start().then(() => {
	console.log('启动连接');
});
// 断开连接
connection.onclose(async () => {
	console.log('断开连接');
});

connection.onreconnected(()=>{
    console.log('服务器已断线...'); 
})

// 重连成功
connection.onreconnected(() => {
	console.log('重连成功');
});

connection.on('OnlineUserList', (vv) => {
    console.log('在线用户列表', vv);
    
});

export const startSignalR =async ()=>{
    await connection.start()
    console.log("连接成功");
}

export const stopSignalR =async ()=>{
    await connection.stop()
    console.log("断开连接");
}

export { connection as signalR };